use crate::common::hal;
use hal::adc::{Adc, SampleTime};
use hal::pac;

struct Random {
    adc: Option<Adc<pac::ADC1>>,
}
static mut RNG: Random = Random { adc: None };

fn get_random(buf: &mut [u8]) -> Result<(), getrandom::Error> {
    for res in buf {
        let mut random: u8 = 0;
        for _i in 0..8 {
            let mut num = 0;
            for _i in 0..5 {
                let adc_val = unsafe {
                    if let Some(adc) = &mut RNG.adc {
                        adc.read_vref()
                    } else {
                        0
                    }
                };
                num += adc_val & 0x01;
            }
            random = (random << 1) + (num & 0x01) as u8;
        }
        *res = random;
    }
    Ok(())
}

pub fn init(mut adc: Adc<pac::ADC1>) {
    adc.set_sample_time(SampleTime::T_1);
    unsafe { RNG.adc = Some(adc) }
    getrandom::register_custom_getrandom!(get_random);
}
